﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using SKDB_Matcher.SQL.Database;
using System.Threading;

namespace SKDB_Matcher
{
    public partial class CDBSetupDlg : Form
    {
        private const String STD_SERVER_PATH = "SQLEXPRESS";

        String m_ConfigPath;
        String m_Server;
        String m_Path;
        String m_Username;
        String m_Password;
        Boolean m_AutoConnect;

        int m_ConnectionState = 0;

        public const int CONNECTION_ERROR = 2;
        public const int CONNECTION_UNKNOW = 0;
        public const int CONNECTION_OK = 1;


        public CDBSetupDlg()
        {
            InitializeComponent();
        }

        Boolean First = false;

        public DialogResult ShowDialog(Boolean FirstStart)
        {
            First = FirstStart;
            if(FirstStart)
                if (m_AutoConnect)
                {
                    EnableControls(false);
                    
                    if (CDatabaseHelper.CheckConnection(m_Server, m_Path, m_Username, m_Password))
                    {
                        m_ConnectionState = CONNECTION_OK;
                        return DialogResult.OK;
                    }
                    MessageBox.Show("Connectionerror, please check your data!", "Check connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    EnableControls();
                    
                }
            ShowInTaskbar = FirstStart;
            return ShowDialog();
        }

        private void EnableControls(Boolean value = true)
        {
            tbPassword.Enabled = value;
            tbUsername.Enabled = value;
            cbAuthentification.Enabled = value;
            tbPath.Enabled = value;
            tbServer.Enabled = value;
            btAccept.Enabled = value;
            btCancel.Enabled = value;
            btCheck.Enabled = value;
        }

        private void cbAuthentification_CheckedChanged(object sender, EventArgs e)
        {
            tbUsername.Enabled = cbAuthentification.Checked;
            tbPassword.Enabled = cbAuthentification.Checked;
            if (!cbAuthentification.Checked)
            {
                tbUsername.Text = "";
                tbPassword.Text = "";
            }
        }

        public void Init(String Path)
        {
            m_ConfigPath = Path;
            SetConnectionState(CONNECTION_UNKNOW);
            if (File.Exists(m_ConfigPath))
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(m_ConfigPath);
                    // Connection Settings einlesen
                    XmlNode ConfigNode = xmlDoc.SelectSingleNode("Config");
                    if (ConfigNode != null)
                    {
                        XmlNode ConnectionNode = ConfigNode.SelectSingleNode("Connection");

                        if (CheckConnectionNode(ConnectionNode))
                        {
                            m_AutoConnect = (ConnectionNode.Attributes["AutoConnect"].InnerText == "1");
                            m_Server = ConnectionNode.Attributes["Server"].InnerText;
                            m_Path = ConnectionNode.Attributes["Path"].InnerText;
                            m_Username = ConnectionNode.Attributes["Username"].InnerText;
                            m_Password = ConnectionNode.Attributes["Password"].InnerText;
                        }
                    }


                }
                catch (Exception e)
                {
                    MessageBox.Show("Konfigurationsdatei ist fehlerhaft! (" + e.Message + ")", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                m_Server = System.Windows.Forms.SystemInformation.ComputerName.ToString();
                m_Path = STD_SERVER_PATH;
            }

            tbServer.Text = m_Server;
            tbPath.Text = m_Path;
            cbAutoConnect.Checked = m_AutoConnect;
            if (m_Username != "")
            {
                cbAuthentification.Checked = true;
                tbUsername.Text = m_Username;
                tbPassword.Text = m_Password;
            }

        }

        private void SaveConfig(Boolean ForceOverwrite = false)
        {
            if (!File.Exists(m_ConfigPath) || ForceOverwrite)
            {
                XmlDocument doc = new XmlDocument();
                XmlNode myRoot;
                myRoot = doc.CreateElement("Config");
                XmlNode ConnectionNode = doc.CreateElement("Connection");

                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Server"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Path"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Username"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Password"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("AutoConnect"));

                if (m_AutoConnect)
                    ConnectionNode.Attributes["AutoConnect"].InnerText = "1";
                else
                    ConnectionNode.Attributes["AutoConnect"].InnerText = "0";
                ConnectionNode.Attributes["Server"].InnerText = m_Server;
                ConnectionNode.Attributes["Path"].InnerText = m_Path;
                ConnectionNode.Attributes["Username"].InnerText = m_Username;
                ConnectionNode.Attributes["Password"].InnerText = m_Password;


                myRoot.AppendChild(ConnectionNode);
                doc.AppendChild(myRoot);


                doc.Save(m_ConfigPath);
            }
            else
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(m_ConfigPath);
                XmlNode ConfigNode = xmlDoc.SelectSingleNode("Config");
                if (ConfigNode == null)
                {
                    ConfigNode = xmlDoc.CreateElement("Config");
                    xmlDoc.AppendChild(ConfigNode);
                }

                XmlNode ConnectionNode = ConfigNode.SelectSingleNode("Connection");
                if (ConnectionNode == null)
                {
                    ConnectionNode = xmlDoc.CreateElement("Connection");
                    ConfigNode.AppendChild(ConnectionNode);
                }

                ConnectionNode.Attributes.RemoveAll();
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Server"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Path"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Username"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("Password"));
                ConnectionNode.Attributes.Append(ConnectionNode.OwnerDocument.CreateAttribute("AutoConnect"));

                if (m_AutoConnect)
                    ConnectionNode.Attributes["AutoConnect"].InnerText = "1";
                else
                    ConnectionNode.Attributes["AutoConnect"].InnerText = "0";
                ConnectionNode.Attributes["Server"].InnerText = m_Server;
                ConnectionNode.Attributes["Path"].InnerText = m_Path;
                ConnectionNode.Attributes["Username"].InnerText = m_Username;
                ConnectionNode.Attributes["Password"].InnerText = m_Password;

                xmlDoc.Save(m_ConfigPath);
            }          
        }

        private Boolean CheckConnectionNode(XmlNode node)
        {
            if (node != null)
                if (node.Attributes["AutoConnect"] != null)
                    if (node.Attributes["Server"] != null)
                        if (node.Attributes["Path"] != null)
                            if (node.Attributes["Username"] != null)
                                if (node.Attributes["Password"] != null)
                                    return true;

            return false;
        }

        private void SetConnectionState(int _State)
        {
            if (labelCheck.InvokeRequired)
            {
                labelCheck.Invoke(new MethodInvoker(() => { SetConnectionState(_State); }));
            }
            else
            {
                m_ConnectionState = _State;
                switch (m_ConnectionState)
                {
                    case CONNECTION_ERROR:
                        {
                            labelCheck.Text = "Verbindungsfehler!";
                            break;
                        }
                    case CONNECTION_UNKNOW:
                        {
                            labelCheck.Text = "Verbindung ungeprüft!";
                            break;
                        }
                    case CONNECTION_OK:
                        {
                            labelCheck.Text = "Verbindung erfolgreich!";
                            break;
                        }
                }
                pbCheck.Image = imageList1.Images[_State];
            }
        }

        private void btCheck_Click(object sender, EventArgs e)
        {
            labelCheck.Text = "Verbindung wird getestet";
            new Thread(new ThreadStart(check)).Start();
        }

        private void check()
        {
           if (CDatabaseHelper.CheckConnection(m_Server, m_Path, m_Username, m_Password))
                SetConnectionState(CONNECTION_OK);
            else
                SetConnectionState(CONNECTION_ERROR);
        }

        public void BindConnectionSettings()
        {
            if (m_ConnectionState == CONNECTION_OK)
            {
                CDatabaseHelper.ServerName = m_Server;
                CDatabaseHelper.Path = m_Path;
                CDatabaseHelper.Username = m_Username;
                CDatabaseHelper.Password = m_Password;
            }
        }

        private void tbServer_TextChanged(object sender, EventArgs e)
        {
            m_Server = tbServer.Text;
            SetConnectionState(CONNECTION_UNKNOW);
        }

        private void tbPath_TextChanged(object sender, EventArgs e)
        {
            m_Path = tbPath.Text;
            SetConnectionState(CONNECTION_UNKNOW);
        }

        private void tbUsername_TextChanged(object sender, EventArgs e)
        {
            m_Username = tbUsername.Text;
            SetConnectionState(CONNECTION_UNKNOW);
        }

        private void tbPassword_TextChanged(object sender, EventArgs e)
        {
            m_Password = tbPassword.Text;
            SetConnectionState(CONNECTION_UNKNOW);
        }

        private void btAccept_Click(object sender, EventArgs e)
        {
            if (m_ConnectionState == CONNECTION_OK)
            {
                m_AutoConnect = cbAutoConnect.Checked;
                m_Password = tbPassword.Text;
                m_Username = tbUsername.Text;
                m_Server = tbServer.Text;
                m_Path = tbPath.Text;
                SaveConfig();
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
            else
            {
                MessageBox.Show("Please check connection first!", "Check connectio", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void cbAutoConnect_CheckedChanged(object sender, EventArgs e)
        {
            m_AutoConnect = cbAutoConnect.Checked;
        }

        private void CDBSetupDlg_Load(object sender, EventArgs e)
        {

        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            if(First)
                System.Windows.Forms.Application.Exit();
        }
    }
}
